package com.ztgf.logistics.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.nlp.AipNlp;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.logistics.common.config.MD5Utils;
import com.ztgf.logistics.common.config.YmlConfig;
import com.ztgf.logistics.mapper.LogisticsMapper;
import com.ztgf.logistics.models.bo.LogisticsBO;
import com.ztgf.logistics.models.bo.RequestBO;
import com.ztgf.logistics.models.bo.RequestParamBO;
import com.ztgf.logistics.models.dto.CourierCompanyDTO;
import com.ztgf.logistics.models.dto.LogisticsDTO;
import com.ztgf.logistics.models.service.ILogisticsService;
import com.ztgf.logistics.models.vo.*;
import com.ztgf.order.models.dto.OrderAfterShipDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderInvoiceDTO;
import com.ztgf.order.models.dto.OrderShipDTO;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.vo.OrderReturnCommodityDetailsVO;
import com.ztgf.sys.models.dto.SysAreaDTO;
import com.ztgf.sys.models.dto.SysInvoiceDTO;
import com.ztgf.sys.models.service.ISysAreaService;
import com.ztgf.sys.models.service.ISysInvoiceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * @author: chenyu.wang
 * @date: 2020-05-23 11:36
 * @Description:
 */
@Slf4j
@DubboService
public class LogisticsServiceImpl extends ServiceImpl<LogisticsMapper, LogisticsDTO> implements ILogisticsService {


    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IOrderShipService orderShipService;
    @DubboReference
    private ISysAreaService sysAreaService;
    @DubboReference
    private IOrderAfterShipService orderAfterShipService;
    @DubboReference
    private IOrderInfoService orderInfoService;
    @DubboReference
    private IOrderReturnCommodityService orderReturnCommodityService;
    @DubboReference
    private IOrderInvoiceService orderInvoiceService;
    @DubboReference
    private ISysInvoiceService sysInvoiceService;
    @Autowired
    private CourierCompanyServiceImpl courierCompanyService;
    //物流信息实时查询url
    @Value(value = "${logistics.synQuery.url}")
    private String synQueryUrl;
    //授权key
    @Value(value = "${logistics.synQuery.key}")
    private String synQueryKey;
    //贵司的查询公司编号
    @Value(value = "${logistics.synQuery.customer}")
    private String synQueryCustomer;

    @Value(value = "${map.baidu.appId}")
    private String appId;
    @Value(value = "${map.baidu.apiKey}")
    private String apiKey;
    @Value(value = "${map.baidu.secretKey}")
    private String secretKey;
    /**
     * 开启行政规划解析
     */
    private static final int resultv2 = 1;

    private final static String CHARSET_DEFAULT = "UTF-8";


    @Override
    public String querySyn(LogisticsBO logisticsBO) {
        StringBuilder param = new StringBuilder("{");
        param.append("\"com\":\"").append(logisticsBO.getCom()).append("\"");
        param.append(",\"num\":\"").append(logisticsBO.getNu()).append("\"");
        param.append(",\"phone\":\"").append(logisticsBO.getPhone()).append("\"");
        param.append(",\"from\":\"").append(logisticsBO.getFrom()).append("\"");
        if(StrUtils.isNotEmpty(logisticsBO.getTo())){
            param.append(",\"to\":\"").append(logisticsBO.getTo().trim()).append("\"");
        } else {
            param.append(",\"to\":\"").append(logisticsBO.getTo()).append("\"");
        }

        if (1 == resultv2) {
            param.append(",\"resultv2\":1");
        } else {
            param.append(",\"resultv2\":0");
        }
        param.append("}");
        Map<String, String> params = new HashMap<>();
        params.put("customer", synQueryCustomer);
        String sign = MD5Utils.encode(param + synQueryKey + synQueryCustomer);
        params.put("sign", sign);
        params.put("param", param.toString());
        log.info("param------------------------"+param.toString());
        String post = this.post(params);
        log.info("---------------" + post);
        if (StringUtils.isNotBlank(post)) {
            QueryTrackResp queryTrackResp = JSON.parseObject(post, QueryTrackResp.class);
            log.info("*****快递100返回状态***** : {}", queryTrackResp);
            if (null != queryTrackResp) {
                if (null != queryTrackResp.getStatus() && "200".equals(queryTrackResp.getStatus())) {
                    return post;
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    @Override
    public List<Object> queryLogistics(Long id) {
        List<Object> result = new ArrayList<>();
        List<OrderShipDTO> list = orderShipService.getListByOrderId(id);
        LogisticsBO bo;
        if (isNull(list)) {
            result.add("暂无快递物流信息,请检查物流单号等信息");
            return result;
        }
        for (OrderShipDTO dto : list) {
            //查询订单信息
            OrderInfoDTO orderInfoDTO = orderInfoService.selectById(dto.getOrderId());
            //自己选择物流能查到物流信息
            if (dto.getType() == ZERO || dto.getType() == TWO ) {
                bo = new LogisticsBO();
                bo.setCom(dto.getCompanyCode());//快递公司编码
                bo.setNu(dto.getShipmentNumber());//快递单号
                //bo.setPhone(dto.getLastFourPhoneNumber());//手机号后四位
                bo.setPhone(orderInfoDTO.getUserMobile());//收货人手机号
                bo.setFrom(dto.getDeparture());//出发地
                bo.setTo(dto.getDestination());//目的地
                String dates = this.querySyn(bo);
                if (!StringUtils.isNotBlank(dates)) {
                    result.add("暂无快递物流信息,请检查物流单号等信息");
                    continue;
                }
                LogisticsVO logisticsVO = new LogisticsVO();
                logisticsVO.setLogisticsCompany(dto.getLogisticsCompany());//物流公司/送货员
                logisticsVO.setLogisticsNumber(dto.getShipmentNumber());//快递单号
                logisticsVO.setLogisticsPhone(dto.getContactInformation());//快递联系方式
                QueryTrackResp queryTrackResp = JSON.parseObject(dates, QueryTrackResp.class);
                logisticsVO.setContent(queryTrackResp);//物流信息
                logisticsVO.setType(dto.getType());//物流类型，0选择物流，1自己联系物流
                logisticsVO.setOrderTime(orderInfoDTO.getCreateTime());//下单时间
                logisticsVO.setShipTime(dto.getCreateTime());//发货时间
                result.add(logisticsVO);
            } else {
                String dates = "您的订单是自己联系物流，" + "物流公司/送货员:" + dto.getLogisticsCompany() + ","
                        + "物流单号:" + dto.getShipmentNumber() + "," + "联系方式:" + dto.getContactInformation()
                        + "," + "您可以自己联系查询!";
                LogisticsAutoVO logisticsAutoVO = new LogisticsAutoVO();
                logisticsAutoVO.setLogisticsCompany(dto.getLogisticsCompany());//物流公司/送货员
                logisticsAutoVO.setLogisticsNumber(dto.getShipmentNumber());//快递单号
                logisticsAutoVO.setLogisticsPhone(dto.getContactInformation());//快递联系方式
                logisticsAutoVO.setContent(dates);//物流信息
                logisticsAutoVO.setShipTime(dto.getCreateTime());//发货时间
                logisticsAutoVO.setOrderTime(dto.getCreateTime());//下单时间
                logisticsAutoVO.setType(dto.getType());//物流类型，0选择物流，1自己联系物流
                result.add(logisticsAutoVO);
            }
        }
        return result;
    }

    @Override
    public List<Object> queryAfterLogistics(Long id) {
        List<OrderAfterShipDTO> list = orderAfterShipService.getListByOrderId(id);
        List<Object> result = new ArrayList<>();
        if (isNull(list)) {
            result.add("暂无快递物流信息,请检查物流单号等信息");
            return result;
        }
        for (OrderAfterShipDTO dto : list) {
            //查询售后订单信息
            OrderReturnCommodityDetailsVO detailsById = orderReturnCommodityService.getDetailsById(dto.getOrderId());
            //自己选择物流能查到物流信息
            if (dto.getType() == ZERO || dto.getType() == 2) {
                LogisticsBO bo = new LogisticsBO();
                bo.setCom(dto.getCompanyCode());//快递公司编码
                bo.setNu(dto.getShipmentNumber());//快递单号
                //bo.setPhone(dto.getLastFourPhoneNumber());//手机号后四位
                bo.setPhone(detailsById.getContactPhone());//联系电话
                bo.setFrom(dto.getDeparture());//出发地
                bo.setTo(dto.getDestination());//目的地
                String dates = this.querySyn(bo);
                if (!StringUtils.isNotBlank(dates)) {
                    result.add("暂无快递物流信息,请检查物流单号等信息");
                    continue;
                }
                LogisticsVO logisticsVO = new LogisticsVO();
                logisticsVO.setLogisticsCompany(dto.getLogisticsCompany());//物流公司/送货员
                logisticsVO.setLogisticsNumber(dto.getShipmentNumber());//快递单号
                logisticsVO.setLogisticsPhone(dto.getContactInformation());//快递联系方式
                QueryTrackResp queryTrackResp = JSON.parseObject(dates, QueryTrackResp.class);
                logisticsVO.setContent(queryTrackResp);//物流信息
                logisticsVO.setType(dto.getType());//物流类型，0选择物流，1自己联系物流
                logisticsVO.setOrderTime(detailsById.getOrderTime());//下单时间
                logisticsVO.setShipTime(dto.getCreateTime());//发货时间
                result.add(logisticsVO);
            } else {
                String dates = "您的订单是自己联系物流，" + "物流公司/送货员:" + dto.getLogisticsCompany() + ","
                        + "物流单号:" + dto.getShipmentNumber() + "," + "联系方式:" + dto.getContactInformation()
                        + "," + "您可以自己联系查询!";
                LogisticsAutoVO logisticsAutoVO = new LogisticsAutoVO();
                logisticsAutoVO.setLogisticsCompany(dto.getLogisticsCompany());//物流公司/送货员
                logisticsAutoVO.setLogisticsNumber(dto.getShipmentNumber());//快递单号
                logisticsAutoVO.setLogisticsPhone(dto.getContactInformation());//快递联系方式
                logisticsAutoVO.setContent(dates);//内容
                logisticsAutoVO.setShipTime(dto.getCreateTime());//发货时间
                logisticsAutoVO.setOrderTime(detailsById.getOrderTime());//下单时间
                logisticsAutoVO.setType(dto.getType());//物流类型，0选择物流，1自己联系物流
                result.add(logisticsAutoVO);
            }
        }
        return result;
    }

    /*
     * @description:获取订单最近一条物流信息
     * @author: chenyu.wang
     * @date: 2020-09-23
     * @return:
     */
    @Override
    public List<Object> queryRecentLogistics(Long orderId) {
        List<Object> result = new ArrayList<>();
        Wrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        List<OrderShipDTO> dtoList = orderShipService.selectList(wrapper);
        if (isNull(dtoList)) {
            result.add("暂无快递物流信息,请检查物流单号等信息");
            return result;
        }
        for (OrderShipDTO orderShipDTO : dtoList) {
            if (orderShipDTO.getType() == 0) {
                LogisticsBO logisticsBO = new LogisticsBO();
                logisticsBO.setCom(orderShipDTO.getCompanyCode());//编码
                logisticsBO.setNu(orderShipDTO.getShipmentNumber());//快递单号
                logisticsBO.setPhone(orderShipDTO.getLastFourPhoneNumber());//手机号码后四位
                logisticsBO.setFrom(orderShipDTO.getDeparture());//出发地
                logisticsBO.setTo(orderShipDTO.getDestination());//目的地
                String query = this.querySyn(logisticsBO);
                if (!StringUtils.isNotBlank(query)) {
                    result.add("暂无快递物流信息,请检查物流单号等信息");
                    continue;
                } else {
                    JSONObject object = JSONObject.parseObject(query);
                    JSONArray data = object.getJSONArray("data");
                    result.add(data.get(0));
                }
            } else {
                String dates = "您的订单是自己联系物流，" + "物流公司/送货员:" + orderShipDTO.getLogisticsCompany() + ","
                        + "物流单号:" + orderShipDTO.getShipmentNumber() + "," + "联系方式:" + orderShipDTO.getContactInformation()
                        + "," + "您可以自己联系查询!";
                result.add(dates);
            }
        }
        return result;
    }

    /*
     * @description:获取售后订单最后一条物流信息
     * @author: chenyu.wang
     * @date: 2020-09-23
     * @return:
     */
    @Override
    public List<Object> queryAfterRecentLogistics(Long afterOrderId) {
        List<Object> result = new ArrayList<>();
        Wrapper<OrderAfterShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", afterOrderId);
        List<OrderAfterShipDTO> dtoList = orderAfterShipService.selectList(wrapper);
        if (isNull(dtoList)) {
            result.add("暂无快递物流信息,请检查物流单号等信息");
            return result;
        }
        for (OrderAfterShipDTO orderShipDTO : dtoList) {
            if (orderShipDTO.getType() == 0) {
                LogisticsBO logisticsBO = new LogisticsBO();
                logisticsBO.setCom(orderShipDTO.getCompanyCode());//编码
                logisticsBO.setNu(orderShipDTO.getShipmentNumber());//快递单号
                logisticsBO.setPhone(orderShipDTO.getLastFourPhoneNumber());//手机号码后四位
                logisticsBO.setFrom(orderShipDTO.getDeparture());//出发地
                logisticsBO.setTo(orderShipDTO.getDestination());//目的地
                String query = this.querySyn(logisticsBO);
                if (!StringUtils.isNotBlank(query)) {
                    result.add("暂无快递物流信息,请检查物流单号等信息");
                    continue;
                } else {
                    JSONObject object = JSONObject.parseObject(query);
                    JSONArray data = object.getJSONArray("data");
                    result.add(data.get(0));
                }
            } else {
                String dates = "您的订单是自己联系物流，" + "物流公司/送货员:" + orderShipDTO.getLogisticsCompany() + ","
                        + "物流单号:" + orderShipDTO.getShipmentNumber() + "," + "联系方式:" + orderShipDTO.getContactInformation()
                        + "," + "您可以自己联系查询!";
                result.add(dates);
            }
        }
        return result;
    }

    @Override
    public List<String> queryAdvanceOrderLogistics(Long orderId) {
        List<String> result = new ArrayList<>();
        // 1、查询订单发货信息
        Wrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("type", 0);
        List<OrderShipDTO> shipDtoList = orderShipService.selectList(wrapper);
        if (isNull(shipDtoList)) {
            return null;
        }
        for (OrderShipDTO dto : shipDtoList) {
            LogisticsBO logisticsBo = new LogisticsBO();
            logisticsBo.setCom(dto.getCompanyCode());
            logisticsBo.setNu(dto.getShipmentNumber());
            logisticsBo.setPhone(dto.getLastFourPhoneNumber());
            logisticsBo.setFrom(dto.getDeparture());
            logisticsBo.setTo(dto.getDestination());
            // 2、查询物流信息，为空跳出循环
            String querySyn = this.querySyn(logisticsBo);
            if (!StringUtils.isNotBlank(querySyn)) {
                continue;
            }
            result.add(querySyn);
        }
        return result;
    }

    @Override
    public Result<?> queryOrderInvoiceLogisticsInformation(Long orderInvoiceId) {
        // 查询订单发票信息
        OrderInvoiceDTO orderInvoiceDTO = orderInvoiceService.selectById(orderInvoiceId);
        if (orderInvoiceDTO == null) {
            return new Result<>(CodeEnum.WULIU_ERROR);
        }
        // 自己选择物流
        if (orderInvoiceDTO.getLogisticsType().equals(1)) {
            return new Result<>(CodeEnum.WULIU_ERROR);
        }
        // 选择物流,如果快递编码和物流编号为空则不让查
        if (CustomizeUtil.strIsNotNull(orderInvoiceDTO.getCompanyName()) && CustomizeUtil.strIsNotNull(orderInvoiceDTO.getNumberPhone())) {
            // 查询快递公司编码
            if (orderInvoiceDTO.getCompanyName().equals("德邦物流")){
                orderInvoiceDTO.setCompanyName("德邦");
            }
            Wrapper<CourierCompanyDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("company_name", orderInvoiceDTO.getCompanyName());
            CourierCompanyDTO courierCompanyDTO = courierCompanyService.selectOne(wrapper);
            if (courierCompanyDTO == null) {
                return new Result<>(CodeEnum.WULIU_ERROR);
            }
            HttpResult httpResult = this.doPost(courierCompanyDTO.getCompanyCode(), orderInvoiceDTO.getNumberPhone());
            log.info("物流信息查询结果:{}", JSONObject.toJSONString(httpResult));
            int status = httpResult.getStatus();
            // 200查询成功
            if (status == 200) {
                return new Result<>(httpResult);
            } else {
                return new Result<>(CodeEnum.WULIU_ERROR);
            }
        }
        return new Result<>(CodeEnum.WULIU_ERROR);
    }

    @Override
    public Result<?> querySysInvoiceLogisticsInformation(Long sysInvoiceId) {
        SysInvoiceDTO sysInvoiceDTO = sysInvoiceService.selectById (sysInvoiceId);
        if (sysInvoiceDTO == null) {
            return new Result<>(CodeEnum.WULIU_ERROR);
        }
        // 自己选择物流
        if (sysInvoiceDTO.getLogisticsType().equals(1)) {
            return new Result<>(CodeEnum.WULIU_ERROR);
        }

        // 选择物流,如果快递编码和物流编号为空则不让查
        if (CustomizeUtil.strIsNotNull(sysInvoiceDTO.getCompanyName()) && CustomizeUtil.strIsNotNull(sysInvoiceDTO.getNumberPhone())) {
            if (sysInvoiceDTO.getCompanyName().equals("德邦物流")){
                sysInvoiceDTO.setCompanyName("德邦");
            }
            // 查询快递公司编码
            Wrapper<CourierCompanyDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("company_name", sysInvoiceDTO.getCompanyName());
            CourierCompanyDTO courierCompanyDTO = courierCompanyService.selectOne(wrapper);
            if (courierCompanyDTO == null) {
                return new Result<>(CodeEnum.WULIU_ERROR);
            }
            HttpResult httpResult = this.doPost(courierCompanyDTO.getCompanyCode(), sysInvoiceDTO.getNumberPhone());
            log.info("物流信息查询结果:{}", JSONObject.toJSONString(httpResult));
            int status = httpResult.getStatus();
            // 200查询成功
            if (status == 200) {
                return new Result<>(httpResult);
            } else {
                return new Result<>(CodeEnum.WULIU_ERROR);
            }
        }
        return new Result<>(CodeEnum.WULIU_ERROR);
    }

    @Override
    public Result<?> queryDepponList(String mailNo) {
        HttpResult httpResult = this.doPost("debangkuaidi", mailNo);
        log.info("物流信息查询结果:{}", JSONObject.toJSONString(httpResult));
        int status = httpResult.getStatus();
        // 200查询成功
        if (status == 200) {
            return new Result<>(httpResult);
        } else {
            return new Result<>(CodeEnum.WULIU_ERROR);
        }
    }

    @Override
    public List<Object> queryLogisticsByWx(String mailNo) {
       List<Object> result = new ArrayList<>();
//        EntityWrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("shipment_number",mailNo);
//        OrderShipDTO dto = orderShipService.selectOne(wrapper);
//        if (dto==null){
//            return result;
//        }
        LogisticsBO  bo = new LogisticsBO();
        bo.setCom("debangkuaidi");//快递公司编码
        bo.setNu(mailNo);//快递单号
//        bo.setPhone(dto.getLastFourPhoneNumber());//手机号后四位
//        bo.setFrom(dto.getDeparture());//出发地
//        bo.setTo(dto.getDestination());//目的地
        String dates = this.querySyn(bo);

        if (!StringUtils.isNotBlank(dates)) {
            return result;
        }
        QueryTrackResp queryTrackResp = JSON.parseObject(dates, QueryTrackResp.class);
        result.add(queryTrackResp);
        return result;
    }

    @Override
    public Result<?> addressProcessing(String address) {
        AipNlp client = new AipNlp(appId, apiKey, secretKey);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        // client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //  client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();

        // 地址识别接口
        org.json.JSONObject res1 = client.address(address, options);
        if (res1==null){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        AdressVO adressVO = new AdressVO();
        log.info("===========response"+res1);
        try {
            if (res1.get("province")!=null || res1.get("county")!=null || res1.get("city")!=null){
                SysAreaDTO province = findArea(String.valueOf(res1.get("province_code")), 1);
                SysAreaDTO city = findArea(String.valueOf(res1.get("city_code")), 2);
                SysAreaDTO county = findArea(String.valueOf(res1.get("county_code")), 3);
                if (province!=null || city!=null || county!=null){
                    if (province==null || city==null || county==null){
                        if (res1.get("phonenum")==null && res1.get("detail")==null && res1.get("person")==null){
                            return new Result<>(CodeEnum.FAIL_100002);
                        }
                    }
                    if (province==null){
                        if (res1.get("phonenum")==null && res1.get("detail")==null && res1.get("person")==null){
                            return new Result<>(CodeEnum.FAIL_100002);
                        }else {
                            adressVO.setName(String.valueOf(res1.get("person")));
                            adressVO.setPhone(String.valueOf(res1.get("phonenum")));
                            adressVO.setDetailAdress(String.valueOf(res1.get("detail")));
                            if (res1.get("town")!=null){
                                adressVO.setDetailAdress(res1.get("town")+String.valueOf(res1.get("detail")));
                            }
                            return new Result<>(adressVO);
                        }
                    }else {
                        adressVO.setProvenceName(province.getName());
                        adressVO.setProvenceCode(province.getCode());
                    }
                    if (city==null){
                        if (res1.get("phonenum")==null && res1.get("detail")==null && res1.get("person")==null){
                            return new Result<>(CodeEnum.FAIL_100002);
                        }else {
                            adressVO.setName(String.valueOf(res1.get("person")));
                            adressVO.setPhone(String.valueOf(res1.get("phonenum")));
                            adressVO.setDetailAdress(String.valueOf(res1.get("detail")));
                            if (res1.get("town")!=null){
                                adressVO.setDetailAdress(res1.get("town")+String.valueOf(res1.get("detail")));
                            }
                            return new Result<>(adressVO);
                        }
                    }else {
                        adressVO.setCityName(city.getName());
                        adressVO.setCityCode(city.getCode());
                    }
                    if(county!=null){
                        adressVO.setCountName(county.getName());
                        adressVO.setCountCode(county.getCode());
                    }
                    adressVO.setName(String.valueOf(res1.get("person")));
                    adressVO.setPhone(String.valueOf(res1.get("phonenum")));
                    adressVO.setDetailAdress(String.valueOf(res1.get("detail")));
                    if (res1.get("town")!=null){
                        adressVO.setDetailAdress(res1.get("town")+String.valueOf(res1.get("detail")));
                    }

                }else {
                    if (res1.get("phonenum")==null && res1.get("detail")==null && res1.get("person")==null){
                        return new Result<>(CodeEnum.FAIL_100002);
                    }else {
                        adressVO.setName(String.valueOf(res1.get("person")));
                        adressVO.setPhone(String.valueOf(res1.get("phonenum")));
                        adressVO.setDetailAdress(String.valueOf(res1.get("detail")));
                        if (res1.get("town")!=null){
                            adressVO.setDetailAdress(res1.get("town")+String.valueOf(res1.get("detail")));
                        }
                    }
                }
            }else {
                if (res1.get("phonenum")==null && res1.get("detail")==null && res1.get("person")==null){
                    return new Result<>(CodeEnum.FAIL_100002);
                }else {
                    adressVO.setName(String.valueOf(res1.get("person")));
                    adressVO.setPhone(String.valueOf(res1.get("phonenum")));
                    adressVO.setDetailAdress(String.valueOf(res1.get("detail")));
                    if (res1.get("town")!=null){
                        adressVO.setDetailAdress(res1.get("town")+String.valueOf(res1.get("detail")));
                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new Result<>(adressVO);
    }
    // "类型 类型：0国家，1省市、2市、3区"
private SysAreaDTO findArea(String code,Integer type){
    EntityWrapper<SysAreaDTO> wrapper = new EntityWrapper<>();
    wrapper.eq("code",code);
    wrapper.eq("type",type);
   return sysAreaService.selectOne(wrapper);
}
    /**
     * @return : com.ztgf.logistics.models.vo.HttpResult
     * @Author :chenyu.wang
     * @Description : 物流信息查询接口
     * @Date : 2021.03.29 10:36
     * @Param : [com:物流公司编码, num:快递编号]
     **/
    private HttpResult doPost(String com, String num) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse resp = null;
        // 参数
        RequestParamBO requestParamBO = new RequestParamBO();
        requestParamBO.setCom(com);
        requestParamBO.setNum(num);
        String parameter = JSONObject.toJSONString(requestParamBO);
        // sign
        String sign = MD5Utils.encode(parameter + synQueryKey + synQueryCustomer);
        RequestBO requestBO = new RequestBO();
        requestBO.setCustomer(synQueryCustomer);
        requestBO.setSign(sign);
        requestBO.setParam(parameter);
        // 响应信息
        HttpResult result = new HttpResult();
        try {
            Map<String, String> params = this.objectToMap(requestBO);
            HttpPost httpPost = new HttpPost(synQueryUrl);
            if (params != null && params.size() > 0) {
                List<NameValuePair> list = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(list, CHARSET_DEFAULT));
            }
            resp = httpClient.execute(httpPost);
            String body = EntityUtils.toString(resp.getEntity(), CHARSET_DEFAULT);
            int statusCode = resp.getStatusLine().getStatusCode();
            result.setStatus(statusCode);
            result.setBody(body);
        } catch (Exception e) {
            log.error("快递100查询接口错误信息:{}", e.getMessage());
            e.printStackTrace();
        } finally {
            if (null != resp) {
                try {
                    resp.close();
                } catch (IOException e) {
                    log.error("快递100查询接口错误信息:{}", e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * description: 发送post请求
     * param: [params]
     * author: chenyu.wang
     * date: 2020-05-23
     * return: java.lang.String
     */
    public String post(Map<String, String> params) {
        StringBuilder response = new StringBuilder();
        BufferedReader reader = null;
        try {
            StringBuilder builder = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (builder.length() > 0) {
                    builder.append('&');
                }
                builder.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                builder.append('=');
                builder.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] bytes = builder.toString().getBytes(StandardCharsets.UTF_8);
            URL url = new URL(synQueryUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(bytes);
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response.toString();
    }

    private Map<String, String> objectToMap(Object obj) throws IllegalAccessException {
        if (obj == null) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        List<Field> allField = this.getAllField(obj);
        for (Field field : allField) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String fieldValue = "";
            if (field.getType() == String.class || field.getType() == Integer.class || field.getType() == int.class) {
                fieldValue = field.get(obj) == null ? "" : field.get(obj).toString();
            }
            map.put(fieldName, fieldValue);
        }
        return map;
    }

    private List<Field> getAllField(Object obj) {
        List<Field> fieldList = new ArrayList<>();
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fieldList;
    }


}
